package com.lq.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lq.payment.entity.Payment;
import com.lq.payment.feign.OrderFeignClient;
import com.lq.payment.mapper.PaymentMapper;
import com.lq.payment.service.IPaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lq.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 支付记录表 服务实现类
 * </p>
 *
 * @author lq
 * @since 2025-08-23
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements IPaymentService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Override
    public Payment getByOrderId(Long orderId) {
        QueryWrapper<Payment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        return getOne(queryWrapper);
    }

    @Override
    public boolean createPayment(Payment payment) {
        // 从订单服务获取订单信息
        try {
            Result orderResult = orderFeignClient.getOrderById(payment.getOrderId());
            if (orderResult != null && orderResult.getSuccess()) {
                // 这里应该解析订单信息并验证支付金额等
                // 为简化示例，我们直接创建支付记录
            }
        } catch (Exception e) {
            // 如果无法获取订单信息，记录日志并继续处理
        }

        payment.setCreateTime(LocalDateTime.now());
        payment.setUpdateTime(LocalDateTime.now());
        return save(payment);
    }

    @Override
    public boolean updatePaymentStatus(Long paymentId, Integer status) {
        Payment payment = getById(paymentId);
        if (payment != null) {
            payment.setStatus(status);
            payment.setUpdateTime(LocalDateTime.now());
            
            // 如果是已支付状态，则设置支付时间
            if (status == 1) {
                payment.setPayTime(LocalDateTime.now());
            }
            
            return updateById(payment);
        }
        return false;
    }
}